package com.axend.sofa.ui.activity

import android.content.DialogInterface
import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.widget.AppCompatImageButton
import androidx.appcompat.widget.AppCompatImageView
import cn.com.heaton.blelibrary.ble.Ble
import cn.com.heaton.blelibrary.ble.model.BleDevice
import cn.com.heaton.blelibrary.ble.utils.ByteUtils
import com.alibaba.android.arouter.core.LogisticsCenter
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.axend.sofa.base.BaseBleVVDActivity
import com.axend.lib_base.ext.click
import com.axend.lib_base.ext.longClick
import com.axend.lib_base.help.ble.BleClient
import com.axend.lib_base.help.ble.BleMsgProcessor
import com.axend.lib_base.help.ble.enums.BleCommandTag
import com.axend.lib_base.livedatabus.LiveDatabus
import com.axend.lib_base.utils.ActivityManage
import com.axend.lib_base.utils.inputfilter.DecimalDigitsInputFilter
import com.axend.lib_base.view.CustomSettingItemView
import com.axend.lib_base.view.dialog.CustomCalibrationDialog
import com.axend.lib_base.view.dialog.CustomInputDialog
import com.axend.lib_service.ARouterPath
import com.axend.lib_service.Constant
import com.axend.sofa.BR
import com.axend.sofa.R
import com.axend.sofa.databinding.ActivitySensorBinding
import com.axend.sofa.viewmodel.SensorViewModel

/**
 * @description 设备页
 * @author admins
 * @time 2025/3/3 13:59
 */
@Route(path = ARouterPath.ACTIVITY_MAIN_SENSOR)
class SensorActivity : BaseBleVVDActivity<SensorViewModel, ActivitySensorBinding>() {

    /*api24推荐方法*/
    private val startActivityForResult =
        registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { result ->
            if (result.resultCode == RESULT_OK) {
                val data: Intent? = result.data
                // 处理返回的数据
                val resultData = data?.getStringExtra("result_key")
                // 处理 resultData
            }
        }

    /*校准弹窗*/
    private val dialog: CustomCalibrationDialog by lazy {
        CustomCalibrationDialog(
            this,
            { dialog.dismiss()}
        ) {
            /*停止学习*/
            mViewModel.writeBleMsg(
                BleMsgProcessor.encodeMsg(
                    BleCommandTag.SET_STUDY_END.getMarkFixCommand(),
                    BleCommandTag.SET_STUDY_END
                )
            )
        }
    }

    override fun init(savedInstanceState: Bundle?) {
        super.init(savedInstanceState)
        mBinding.setVariable(BR.viewmodel, mViewModel)
        mBinding.executePendingBindings()

        initClick()
        initObserver()

    }

    private fun initObserver() {
        mViewModel.dialogModel.observe(this) {
            dialog.setModel(it)
        }
    }

    private fun initClick() {
        /*编辑事件*/
        mBinding.rlEdit.click {
            // 使用 ARouter 启动 SelectModelActivity 并请求结果
            val postcard = ARouter.getInstance().build(ARouterPath.ACTIVITY_SELECT_MODEL)
                .withInt(Constant.ROUTER_KEY_MODEL_SELECT, mViewModel.sofaModel.value!!)
                .navigation(this)
//            LogisticsCenter.completion(postcard)
//            startActivityForResult.launch(Intent(this, postcard.destination))
        }
        /*日志*/
        mBinding.titleBar.rightLayout.click {
            ARouter.getInstance().build(ARouterPath.ACTIVITY_LOG).navigation(this)
        }
        /*沙发门限1*/
        mBinding.csThresh1.setOnClickListener(CustomSettingItemView.OnClickListener {
            CustomInputDialog(
                this,
                getString(com.axend.lib_base.R.string.app_dialog_input_value),
                object : CustomInputDialog.OnOkListener {
                    override fun onClick(dialog: DialogInterface, value: Float) {
                        mViewModel.writeBleMsg(
                            BleMsgProcessor.encodeMsg(value, BleCommandTag.SET_SOFA_DOOR_SILL),
                            value
                        )
                        dialog.dismiss()
                    }

                }).setInputValueFilter(DecimalDigitsInputFilter(5, 0)).show()
        })
        /*沙发门限2*/
        mBinding.csThresh2.setOnClickListener(CustomSettingItemView.OnClickListener {
            CustomInputDialog(
                this,
                getString(com.axend.lib_base.R.string.app_dialog_input_value),
                object : CustomInputDialog.OnOkListener {
                    override fun onClick(dialog: DialogInterface, value: Float) {
                        mViewModel.writeBleMsg(
                            BleMsgProcessor.encodeMsg(value, BleCommandTag.SET_SOFA_DOOR_SILL2),
                            value
                        )
                        dialog.dismiss()
                    }

                }).setInputValueFilter(DecimalDigitsInputFilter(5, 0)).show()
        })
        /*沙发上升长按*/
        mBinding.btUp.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    v.setBackgroundResource(com.axend.lib_base.R.drawable.shape_circle_blue)
                    (v as AppCompatImageButton).setImageResource(com.axend.lib_base.R.drawable.icon_up2)
                    mViewModel.bleSofaAction(1u)
                    true
                }

                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    // 如果需要在长按结束时发送停止命令，可以在这里处理
                    v.setBackgroundResource(com.axend.lib_base.R.drawable.shape_circle_white)
                    (v as AppCompatImageButton).setImageResource(com.axend.lib_base.R.drawable.icon_up)
                    mViewModel.bleSofaAction(2u)
                    true
                }

                else -> false
            }
        }

        /*沙发停止*/
        mBinding.btPause.click {
            mViewModel.bleSofaAction(2u)
        }
        /*沙发下降*/
        mBinding.btDown.setOnTouchListener { v, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    v.setBackgroundResource(com.axend.lib_base.R.drawable.shape_circle_blue)
                    (v as AppCompatImageButton).setImageResource(com.axend.lib_base.R.drawable.icon_down2)
                    mViewModel.bleSofaAction(3u)
                    true
                }

                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    // 如果需要在长按结束时发送停止命令，可以在这里处理
                    v.setBackgroundResource(com.axend.lib_base.R.drawable.shape_circle_white)
                    (v as AppCompatImageButton).setImageResource(com.axend.lib_base.R.drawable.icon_down)
                    mViewModel.bleSofaAction(2u)
                    true
                }

                else -> false
            }
        }

        /*校准页面*/
        mBinding.csCalibration.setOnClickListener(CustomSettingItemView.OnClickListener {
//            ARouter.getInstance().build(ARouterPath.ACTIVITY_CALIBRATION)
//                .withTransition(
//                    com.axend.lib_base.R.anim.base_slide_right_in,
//                    com.axend.lib_base.R.anim.base_slide_right_out
//                )
//                .navigation(this)
            /*开始学习*/
            mViewModel.writeBleMsg(
                BleMsgProcessor.encodeMsg(
                    BleCommandTag.GET_VERSION.getMarkFixCommand(),
                    BleCommandTag.SET_STUDY_START
                )
            )
        })

        /*固件更新页面*/
        mBinding.csFirmware.setOnClickListener(CustomSettingItemView.OnClickListener {
            ARouter.getInstance().build(ARouterPath.ACTIVITY_FIRMWARE_UPDATE)
                .withString(Constant.ROUTER_KEY_FIRMWARE_VERSION, mViewModel.firmwareVersion.value)
                .withTransition(
                    com.axend.lib_base.R.anim.base_slide_right_in,
                    com.axend.lib_base.R.anim.base_slide_right_out
                )
                .navigation(this)
        })
    }


    override fun onResume() {
        super.onResume()
        /*必须要选择型号后才获取*/
        mViewModel.initAndSendDataQueue()



    }


    override fun onDestroy() {
        super.onDestroy()
    }

}